// import { User } from '@/services/quest';
import { RtcDefaultApi } from '@/unit/axios';
import { defaultErrorHandler } from '@/unit/error-handler';
import { success, warning } from '@/unit/message';
import { NavigateTo } from '@/unit/navigate-to';
import {
  action,
  computed,
  makeObservable,
  observable,
} from 'mobx';
import { singleton } from 'tsyringe';
import {
  getToken,
  removeToken,
  setToken,
} from '../../unit/tokens';
import { Result, User } from './type';

@singleton()
export class Login {
  /** token */
  @observable
  public token: string | null = getToken();

  @observable
  public count: number = 0;

  @observable
  public username: string = '';

  @observable public passwordAgain: string = '';

  @observable public password: string = '';

  @observable public userInfo: User = new User();

  @action
  public setName = (username: string) => {
    this.username = username;
  };

  @action public setPassword = (password: string) => {
    this.password = password;
  };

  @action public setPasswordAgain = (password: string) => {
    this.passwordAgain = password;
  };

  /**
   * 登录
   */
  @action public async login() {
    try {
      const result = (await RtcDefaultApi.apiAuthLoginPost({
        username: this.username,
        password: this.password,
      })) as unknown as Result;
      if (result) {
        this.changeToken(result.token);
        this.changeUser(result.user);

        success('登录成功！');

        NavigateTo('home');
      }
    } catch (error) {
      defaultErrorHandler(error);
    }
  }

  /**
   * 获取登录状态
   */
  @action public index = async () => {
    try {
      const result = await RtcDefaultApi.apiUserIndexGet();
      if (result) {
        this.changeUser(result);
      }
    } catch (error) {
      defaultErrorHandler(error);
    }
  };

  /**
   * 用户注册
   * @returns
   */
  @action public register = async () => {
    try {
      if (this.password !== this.passwordAgain) {
        warning('两次密码不一致');
        return;
      }

      const result =
        await RtcDefaultApi.apiUserRegisterPost({
          password: this.password,
          username: this.username,
        });

      if (result) {
        success('注册成功');
      }
    } catch (error) {
      defaultErrorHandler(error);
    }
  };

  public defaultSelectedKey = '1';

  /** 实时改变token值 */
  @action
  public changeToken(value: string) {
    setToken(value);
    this.token = value;
  }

  @action public changeUser(value: User) {
    this.userInfo = value;
  }

  /** 删除token值 */
  @action
  public clearToken() {
    removeToken();
    this.token = getToken();
  }

  @computed get getCount() {
    return this.count;
  }

  constructor() {
    makeObservable(this);
  }
}
